import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/page/elder_search_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/department_list_data.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_item_content_list.dart';
import 'package:ls_work/net/response/service_item_list.dart';
import 'package:ls_work/ui/select_building_floor_page.dart';
import 'package:ls_work/ui/service_order/department_list_page.dart';
import 'package:ls_work/ui/service_order/service_item_content_page.dart';
import 'package:ls_work/ui/service_order/service_item_list_page.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';

import '../../model/customer_info_model.dart';

class AddServiceOrderViewModel extends BaseViewModel {
  AddServiceOrderViewModel(BuildContext context) : super(context);

  // var repairType = "居家报修";
  var serviceTime = "";
  var formats = [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss];

  var buildingName = "";
  var buildingId  = "";
  var floorName = "";
  var floorId = "";

  var customerModel = CustomerInfoModel();

  ///服务项目
  ServiceItemList? serviceItem;

  ///居家报修老人
  ElderInfo? old;

  ///老人地址
  String oldAddress = "";

  ///服务内容
  ServiceItemContentList? serviceContent;

  ///服务部门
  DepartmentListData? department;

  var remark = "";
  var inputAddress = "";
  var inputHuman = "";

  List<String> files = [];

  ComboDataModel dataModel = ComboDataModel();
  List<CodeValue> repairList = [
    CodeValue(codeValue: "1",nameCn: "在住客户"),
    CodeValue(codeValue: "0",nameCn: "非在住客户")
  ];
  CodeValue? currentType;

  @override
  void onCreated() {
    super.onCreated();
    addModels([dataModel]);
    _initRepairType();
  }

  Future<void> _initRepairType() async {
    // var list = await dataModel.getComboData(ComboDataModel.repairType);
    // repairList = list;
    currentType = repairList[0];
    notifyListeners();
  }

  void selectRepairType() {
    DataPickerView(context, repairList, onSubmitListener: (p1, p2, p3) {
      var item = repairList[p1];
      currentType = item;
      notifyListeners();
    }).show();
  }

  void selectServiceTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      serviceTime = date?.toDateStr(formats)??"";
      notifyListeners();
    });
  }

  Future<void> selectOld() async {
    var data = await Go().push(ElderSearchPage(
      needBack: true,
    ));
    if (data != null) {
      old = data;
      oldAddress = '${old?.floorNo}#${old?.roomNo}';
    }
    notifyListeners();
  }

  ///选择服务项目
  Future<void> selectServiceItem() async {
    var data = await Go().push(ServiceItemListPage());
    if (data != null) {
      serviceItem = data;
      notifyListeners();
    }
  }

  ///选择服务内容
  Future<void> selectServiceContent() async {
    if (serviceItem == null) {
      showToast('请先选择服务项目');
      return;
    }
    var data =
        await Go().push(ServiceItemContentPage(serviceItem?.id.toString()??""));
    if (data != null) {
      serviceContent = data;
      notifyListeners();
    }
  }

  Future<void> selectDepartment() async {
    var data = await Go().push(DepartmentListPage());
    if (data != null) {
      department = data;
      notifyListeners();
    }
  }

  void submitClick() {
    if (currentType?.codeValue == "1") {
      if (old == null) {
        showToast("请选择服务对象");
        return;
      }
    } else {
      // if (inputHuman.isNullOrEmpty()) {
      //   showToast('请输入服务对象');
      //   return;
      // }
      if (inputAddress.isNullOrEmpty()) {
        showToast('请输入服务地点');
        return;
      }
    }

    // if (serviceTime.isNullOrEmpty()) {
    //   showToast('请输入服务时间');
    //   return;
    // }

    if (serviceItem == null) {
      showToast('请选择服务项目');
      return;
    }
    if (serviceContent == null) {
      showToast('请选择服务内容');
      return;
    }
    // if (department == null) {
    //   showToast('请选择服务部门');
    //   return;
    // }
    // showToast(old.roomId.toString());
    createOrder();
  }

  Future<void> createOrder() async {
    var serveId = currentType?.codeValue;
    var serveTypeId = serviceItem?.id.toString();
    var serveItemId = serviceContent?.id.toString();
    var commonAddress =
        currentType?.codeValue == "1" ? oldAddress : inputAddress;
    var commonHuman = currentType?.codeValue == "1" ? old?.name : inputHuman;
    var familyAddressId =
        currentType?.codeValue == "1" ? old?.roomId.toString() : "";
    var familyHumanId = currentType?.codeValue == "1" ? old?.id.toString() : "";
    showLoadingDialog(msg: '提交中...');
    try {
      List<dynamic> uploadFiles = [];
      if (files.isNotEmpty) {
        uploadFiles = await _uploadFiles();
      }

      var data = await PostRequest.createServiceOrder(
          serveId: serveId??"",
          serveTypeId: serveTypeId??"",
          serveItemId: serveItemId??"",
          remark: remark,
          officeId: department == null ? null : department?.officeId.toString(),
          markTime: serviceTime,
          requestType: '10260',
          commonAddress: commonAddress,
          commonHuman: commonHuman??"",
          familyAddressId: familyAddressId??"",
          familyHumanId: familyHumanId??"",
          buildingId: buildingId,
          floorId: floorId,
          attachList: uploadFiles);
      hideDialog();
      var bean = ResponseBean.fromJson(data);
      if ("0" == bean.code) {
        showToast('提交成功');
        sendMessage(SendMessageEvent(MessageConfig.REFRESH_ORDER));
        finish();
      } else {
        showToast(bean.msg??"");
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  ///上传文件
  Future<List<Map<String, dynamic>>> _uploadFiles() async {
    List<Map<String, dynamic>> result = [];
    for (var file in files) {
      var data = await PostRequest.uploadFile(file);
      var bean = ResponseBean.fromJson(data);
      if ('0' == bean.code) {
        result.add(bean.data);
      } else {
        throw bean.msg ?? "";
      }
    }
    return result;
  }

  void selectBuildingAndFloor(){
    Go().push(SelectBuildingFloorPage(callback: (buildingId,floorId,buildingName,floorName){
      finish();
      this.buildingName = buildingName;
      this.buildingId = buildingId;
      this.floorName = floorName;
      this.floorId = floorId;
      notifyListeners();
    },));
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerByCard(cardNumber);

    }
  }

  Future<void> getCustomerByCard(String cardNumber) async {
    showLoadingDialog();
    try{
      var oldData = await customerModel.getCardAccount(physicalCardNo: cardNumber);


      if(currentType?.codeValue=='1'){
        var oldInfo = await customerModel.getElderInfo(oldData.data!.human!.id.toString());
        hideDialog();
        old = oldInfo;
        oldAddress = '${old?.floorNo}#${old?.roomNo}';
      }else{
        hideDialog();
        inputHuman = oldData.data!.human!.name??"";
        // inputAddress = '${/oldInfo?.floorNo}#${oldInfo?.roomNo}';
      }
      notifyListeners();
    }catch(e){
      showToast(e.toNetError());
      hideDialog();
    }
  }
}
